import {Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, Content, AlertController, MenuController} from 'ionic-angular';
import {OrderProvider} from "../../../providers/orderProvider";
import {Cart} from "../../../models/Cart";
import {KitProvider} from "../../../core/foundations/KitProvider";
import {CartProvider} from "../../../providers/cartProvider";
import {DishProvider} from "../../../providers/DishProvider";
import {CustomerProvider} from "../../../providers/customerProvider";
import {CategoryProvider} from "../../../providers/category";
import {Observable} from "rxjs/Observable";
import {ShoppingCartPage} from "../shopping-cart/shopping-cart";
import {OrderNumber,} from "../../../models/OrderNumber";
import {Order} from "../../../models/Order";


/**
 * Generated class for the PlacedOrderPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-placed-order',
  templateUrl: 'placed-order.html',
})
export class PlacedOrderPage {
  @ViewChild(Content) content: Content;
  orders: { OrderNumber: OrderNumber, Orders: Order[], delete?: boolean }[];
  carts: Cart[];
  hasOrder = true;
  Tax: number;
  Tips: number;
  subTotal = 0.00;
  Total = 0.00;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public menu: MenuController,
              public alert: AlertController,
              public auth: CustomerProvider,
              public dishProd: DishProvider,
              public cartProd: CartProvider,
              public kit: KitProvider,
              public cateProd: CategoryProvider,
              public orderProd: OrderProvider) {
  }

  ionViewDidLoad() {
    let loading = this.kit.loadingPresent();
    this.cartProd.getCart().catch(err => {
      loading.dismiss();
      console.log('Error:', err);
      return Observable.throw(err);
    }).subscribe(res => {
      loading.dismiss();
      this.carts = res.data as Cart[];
      console.log('this.carts', this.carts);
      this.subTotal = this.cartProd.total;

      console.log(this.subTotal);
      this.content.resize();
    });
    this.content.resize();

  }

  clear() {
    this.cartProd.clearCart().subscribe(res => {
      this.carts = null;
      this.subTotal = 0;
    });
  }

  placed() {
    this.orderProd.createOrder(this.carts, this.Tax, this.Tips).subscribe(
      res => {
        if (res.success) {
          this.ionViewDidLoad();
          this.content.resize();
        }
        this.orders = res.data;
        console.log(this.Tax);
        console.log(this.orders);
        this.hasOrder = res.data > 0;

        let alert = this.alert.create({
          message: 'Your Order Is Placed',

        });
        alert.present()
      }
    );
  }

  change() {
    this.navCtrl.push(ShoppingCartPage, {})

  }

}
